<template>
  <h1>{{ msg }}</h1>
  <p>{{ counter }}</p>
  <p>{{ doubleCounter }}</p>
  <p ref="desc"></p>
</template>

<script>
import {reactive, computed, onMounted, onUnmounted, ref, toRefs, watch} from 'vue'

export default {
  name: "Composition.vue",
  setup() {
    // const data = reactive({
    //   counter:1,
    //   doubleCounter: computed(() => data.counter * 2)
    // })
    const {counter, doubleCounter} = useCounter()

    const msg = ref('hello world')  // 单值

    // 使用元素的引用
    const desc = ref(null)
    watch(counter, (val, oldVal) =>{
      const p = desc.value
      p.textContent = `counter change from ${oldVal} to ${val}`
    })
    return {counter, doubleCounter, msg, desc}
  }
}


function useCounter () {
  const data = reactive({
    counter:1,
    doubleCounter: computed(() => data.counter * 2)
  })
  let timer;
  onMounted(() => {
    timer = setInterval(() => {
      data.counter++;
    }, 1000)
  })

  onUnmounted( () => {
    clearInterval(timer)
  })
  return toRefs(data)
}
</script>

<style scoped>

</style>
